package geektime.spring.springbucks.service;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import geektime.spring.springbucks.mapper.CoffeeMapper;
import geektime.spring.springbucks.model.Coffee;
import geektime.spring.springbucks.params.PageParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CoffeeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private CoffeeMapper coffeeMapper;

    @Transactional
    public void insert(Coffee c) {
        coffeeMapper.save(c);
    }

    @Transactional
    public void update(Coffee c) {
        coffeeMapper.update(c);
    }

    @Transactional
    public void deleteAll() {
        coffeeMapper.deleteAll();
    }

    public Coffee findById(Long id) {
        Object obj = redisTemplate.opsForValue().get(this.getClass().getName() + "_" + id);
        if (obj == null) {
            Coffee c = coffeeMapper.findById(id);

            try {
                if (c == null) {
                    redisTemplate.opsForValue().set(this.getClass().getName() + "_" + id, "NULL");
                    redisTemplate.expire(this.getClass().getName() + "_" + id, 100, TimeUnit.SECONDS);
                    return null;
                }
                redisTemplate.opsForValue().set(this.getClass().getName() + "_" + id, objectMapper.writeValueAsString(c));
                redisTemplate.expire(this.getClass().getName() + "_" + id, 100, TimeUnit.SECONDS);
                log.info("查询数据为: {}", c);
                return c;
            } catch (JsonProcessingException e) {
                log.info("查询异常", e);

            }
        } else {
            if(obj.toString().equalsIgnoreCase("NULL")){
                return null;
            } else {
                try {
                    Coffee coffee = objectMapper.readValue(obj.toString(), Coffee.class);
                    return coffee;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public PageInfo<Coffee> getPageInfo(PageParam pageParam) {
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        List<Coffee> coffees = coffeeMapper.selectAll();
        PageInfo<Coffee> objectPageInfo = new PageInfo<>(coffees);
        return objectPageInfo;
    }

}
